#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>

struct ListNode
{
    int val;
    struct ListNode* next;
};

int findTheWinner(int n, int k) {
    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;
    int i = 1;
    for (i = 1; i <= n; i++) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = i;
        node->next = NULL;
        if (!head) {
            head = node;
            tail = node;
        }
        else {
            tail->next = node;
            tail = tail->next;
        }
    }
    //tail->next = head;
    //struct ListNode* tmp = head;
    //while (tmp->next = tmp)
    //{
    //    struct ListNode* next = tmp->next;
    //    if (i == k)
    //    {
    //        head->next = tmp->next;
    //        free(tmp);
    //        tmp = next; 
    //        i = 1;
    //        continue;
    //    }
    //    i++;
    //}
    //return tmp->val;
    while (head != tail) {
        for (int i = 1; i < k; i++) {
            struct ListNode* node = head;
            head = head->next;
            tail->next = node;
            tail = tail->next;
            tail->next = NULL;
        }
        struct ListNode* node = head;
        head = head->next;
        free(node);
    }
    int res = head->val;
    free(head);
    return res;
}